<template>
    <div class="header-container">
        <header>
            <img src="../assets/img/logo.png" />
            <ul class="navbar">
                <li><div class="padding" @click='modalVisible = true'> <i class="iconfont icon-remove-site"> </i>  {{$t('home.header.returnOldSolax')}}</div></li>
                <li>
                    <el-dropdown trigger="click" @visible-change="changeAlarmBox">
                        <span class="el-dropdown-link">
                            <i class="iconfont icon-alarm"></i>
                            <i class="iconfont icon-warning-round" v-show="alarmCount!=0"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="alarmBox">
                            <div class="box_header">
                                <p>{{$t('index.showtbl.have')}}<span class="num"> {{alarmCount}} </span>{{$t('index.showtbl.msg')}}</p>
                                <div class="right" v-show="alarmCount!=0"><el-button size="mini" @click="delAllAlarmMsg">{{$t('clear_all')}}</el-button></div>
                            </div>
                            <ul class="box_body">
                                <li v-for="(item,i) in alarmList" :key="item.id">
                                    <el-popover
                                        placement="left"
                                        trigger="hover">
                                        <ul class="popover">
                                            <li>{{$t('site.userName')}}：{{item.userName||'-'}}</li>
                                            <li>{{$t('battery.batterySN')}}：{{item.inverterSn}}</li>
                                            <li>{{$t('device.inverter.wifiSN')}}：{{item.wsn}}</li>
                                            <li v-if="item.errorMessage!=null">{{$t('alarmShowView.thName')}}：{{item.errorMessage}}</li>
                                            <li>{{$t('test.deviceTest.inverterAlarm.happenTime')}}：{{item.timeStringVal}}</li>
                                        </ul>
                                        <el-button slot="reference" class="info">
                                            <i class="iconfont icon-warning"></i>
                                            <div>{{item.userName}} {{item.inverterSn}} {{item.wsn}} {{item.errorMessage!=null?item.errorMessage:''}} {{item.timeStringVal}}</div>
                                            <i class="iconfont icon-check-circle pointer" :title="$t('test.errorHistory.js_errorHistory_treated')" @click="delAlarmMsg(i,item.inverterSn,item.errorCode)"></i>
                                        </el-button>
                                    </el-popover>
                                </li>
                            </ul>
                            <!-- v-show="alarmCount!=0" -->
                            <div class="box_footer" v-show="alarmCount!=0" @click='pushShowMsg'><el-link>{{$t('index.viewAll')}}</el-link></div>
                        </el-dropdown-menu>
                    </el-dropdown>
                </li>
                <li>
                    <el-dropdown trigger="click">
                        <span class="el-dropdown-link">
                            <i class="iconfont icon-person" inner></i>{{userData.loginName}}<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown" class="alarmBox">
                            <ul class="box_body">
                                <li>{{$t('user.loginName')}}：{{userData.loginName}}</li>
                                <li>{{$t('index.loginTime')}}：{{loginTime}}</li>
                                <li>{{$t('vsite.userType')}}：{{returnUserTypeCode(userData.userType)}}</li>
                                <li v-show="userData.firmName">{{$t('index.belongToUnit')}}：{{userData.firmName}}</li>
                                <li v-show="userData.address">{{$t('vsite.vsiteAdd.country')}}：{{userData.address}}</li>
                            </ul>
                            <div class="box_footer handle clearfix" v-show="sample!=1">
                                <span id="cancelUser" :title="$t('agreement.cancelUser')" @click="showDeleteModal()" v-show="userData.userType==5">
                                    <i class="iconfont icon-zhuxiaotouzhuzhanghu"></i>
                                </span>
                                <span id="updateUserName" :title="$t('user.updateUserName.title')" @click="updateUserName">
                                    <i class="iconfont icon-editUser"></i>
                                </span>
                                <span id="updatePassword" :title="$t('user.updatePassword')" @click="pwdFormVisible=true">
                                    <i class="iconfont icon-zhongzhimima"></i>
                                </span>
                            </div>
                        </el-dropdown-menu>
                    </el-dropdown>
                </li>
                <li>
                    <LangSelect></LangSelect>
                </li>
                <li @click="logout">
                    <div class="padding"><i class="iconfont icon-exit" inner></i>{{$t('index.exit')}}</div>
                </li>
            </ul>
        </header>
        <el-dialog 
          :title="$t('user.updatePassword')"
          :visible.sync="pwdFormVisible"
          class="el-dialog-sm"
          :close-on-click-modal='false'>
            <el-row :gutter="24">
                <el-col :span="20">
                    <el-form ref="pwdForm" :model="pwdForm" :rules="rules" label-width="230px">
                        <el-form-item :label="$t('user.updatePassword.oldPwd')" prop="password">
                            <el-input v-model="pwdForm.password" show-password auto-complete="new-accounts"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('user.updatePassword.newPwd')" prop="newPwd">
                            <el-input v-model="pwdForm.newPwd" show-password auto-complete="new-accounts"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('user.updatePassword.conPwd')" prop="confirmPwd">
                            <el-input v-model="pwdForm.confirmPwd" show-password auto-complete="new-accounts"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('pwdForm','pwdFormVisible')">{{$t('cancel')}}</el-button>
                <el-button type="primary" @click="submitPwdForm('pwdForm')">{{$t('sure')}}</el-button>
            </span>
        </el-dialog>

        <el-dialog
          :title="$t('user.updateUserName.title')"
          :visible.sync="nameFormVisible"
          width="700px"
          :close-on-click-modal='false'>
            <el-row :gutter="24">
                <el-col :span="20">
                    <el-form ref="nameForm" :model="nameForm" :rules="rules" label-width="230px">
                        <el-form-item :label="$t('user.loginName')">
                            {{userData.loginName}}
                        </el-form-item>
                        <el-form-item :label="$t('warrantyStatistics.email')" >
                            {{userData.email}}
                            <el-button type="default" size="mini" :disabled="this.codeTime!=0" @click="sendMailCode()">{{codeText}}</el-button>
                        </el-form-item>
                        <el-form-item :label="$t('login.pointCode')" prop="code">
                            <el-input v-model.trim="nameForm.code"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('login.loginUserName')" prop="loginName">
                            <el-input v-model.trim="nameForm.loginName"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('nameForm','nameFormVisible')">{{$t('cancel')}}</el-button>
                <el-button type="primary" @click="submitNameForm('nameForm')">{{$t('sure')}}</el-button>
            </span>
        </el-dialog>
        <el-dialog
          :title="$t('warmPrompt')"
          width="700px"
          :visible.sync="modalVisible"
          :close-on-click-modal='false'>
            <p>{{$t('home.header.returnOldSolax.msg1')}}</p>
            <p>{{$t('home.header.returnOldSolax.msg2')}}</p>
            <p>{{$t('home.header.returnOldSolax.msg3')}}</p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="modalVisible = false">{{$t('label.NO')}}</el-button>
                <el-button type="primary" @click="returnOldSolaxCloud">{{$t('label.YES')}}</el-button>
            </span>
        </el-dialog>
        <emailCodeModal @closeAccount='closeAccount'></emailCodeModal>
    </div>
</template>

<script scoped>
import emailCodeModal from '../views/getUserEmailCode.vue'
import LangSelect from '@/components/LangSelect'
import md5 from 'js-md5'
export default {
    name:'Header',
    components:{
        LangSelect,
        emailCodeModal
    },
    props: {
        sample:''
    },
    data(){
        var validate_oldPwd = (rule, value, callback) => {
            debugger;
            console.log(value)
            console.log(this.userData.password,'password')
            if (md5(value)!=this.userData.password) {
                callback(new Error(this.$t('user.msg_different_pwd')));
            }else{
                callback()
            }
        };
        var validate_newPwd = (rule, value, callback) => {
            var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
		    var regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
            if (regEn.test(value)||regCn.test(value)) {
                callback(new Error(this.$t('user.msg_illegal_character')));
            } else if (value==this.pwdForm.password){
                callback(new Error(this.$t('user.msg_old_equal_newPwd')));
            }else{
                callback()
            }
        };
        var validate_confirmPwd = (rule, value, callback) => {
            if (value!=this.pwdForm.newPwd) {
                callback(new Error(this.$t('user.msg_different_twice')));
            }else{
                callback()
            }
        };
        var validate_code = async(rule, value, callback) => {
            let res = await this.API.regMailCode({
                code:this.nameForm.code,
                loginName:this.userData.loginName
            })
            if(!res){
                callback(new Error(this.$t('user.updateUserName.msg_code_err')));
            }else{
                callback()
            }
        };
        var validate_loginName = (rule, value, callback) => {
            if (!this.Regs.loginName_reg.test(value)) {
                callback(new Error(this.$t('login.LoginNameErr')));
            }else{
                callback()
            }
        };
        return {
            modalVisible:false,
            userData:{},
            alarmList:[],
            alarmCount:0,
            dictionary:{},
            loginTime:sessionStorage.getItem('loginTime'),
            codeText:this.$t('login.pointCode'),
            codeTime:0,
            pwdFormVisible:false,
            pwdForm:{
                password:'',
                newPwd:'',
                confirmPwd:''
            },
            nameFormVisible:false,
            nameForm:{
                loginName:'',
                email:'',
            },
            rules:{
                password:[
                    { required: true, message: this.$t('user.msg_originalPwd'), trigger: 'blur' },
                    { validator: validate_oldPwd, trigger: 'blur' }
                ],
                newPwd:[
                    { required: true, message: this.$t('user.msg_newPwd'), trigger: 'blur' },
                    { min: 2, max: 20, message: this.$t('index_js_lengthRules'), trigger: 'blur' },
                    { validator: validate_newPwd, trigger: 'blur' }
                ],
                confirmPwd:[
                    { required: true, message: this.$t('common.info.pl-insert-sure-pwd'), trigger: 'blur' },
                    { validator: validate_confirmPwd, trigger: 'blur' }
                ],
                code:[
                    { required: true, message: this.$t('login.pointAuthCode'), trigger: 'blur' },
                    { validator: validate_code, trigger: 'blur' }
                ],
                loginName:[
                    { required: true, message: this.$t('login.pointUserName'), trigger: 'blur' },
                    { validator: validate_loginName, trigger: 'blur' }
                ]
            }
        }
    },
    mounted(){
        this.initAlarm()
        this.getUserInfo()
        this.getDictionaryBatch()
    },
    methods:{
        returnOldSolaxCloud(){
            let lan = localStorage.getItem('lang') || 'en_US'
            let type = localStorage.getItem('mapType')
            if(type == 1){
                window.open(`https://cn.solaxcloud.com/i18n/language.do?language=${lan}&url=/views/login.jsp`)
                // window.open(`https://www.baidu.com`)
            }else if(type == 2){
                window.open(`https://old.solaxcloud.com/i18n/language.do?language=${lan}&url=/views/login.jsp`)
            }
            this.modalVisible = false
        },
        changeAlarmBox(val){
            if(val){
                this.initAlarm()
            }
        },
        pushShowMsg(){
            this.initAlarm()
            if(this.$route.fullPath!='/alarmShowView'){
                this.$router.replace({path:'/alarmShowView'})
            }else{
                this.$router.replace({path:'/refresh'})
            }
        },
        updateUserName(){
            if(this.userData.email){
                this.nameFormVisible=true
            }else{
                this.$message.warning(this.$t('index.js_noemail_uname'))
            }
        },
        //发送验证码
        async sendMailCode(){
            this.codeTime=60;
            let interval_code = setInterval(()=>{
                if(this.codeTime<1){
                    this.codeText= this.$t('get_verification_code')
                    clearInterval(interval_code);
                }else{
                    this.codeText=this.codeTime-- +'s'
                }
            },1000)
            let res = await this.API.sendMailCode({
                mail:this.userData.loginName
            })
            if(res){
                this.$message.success(this.$t('login.js_email_Login'))
            }else{
                this.$message.warning(this.$t('login.js_email_sendError'))
            }
        },
        //修改登录账号
        async submitNameForm(formName){
            this.$refs[formName].validate(async(valid)=>{
                if(valid){
                    let res = await this.API.updateLoginName({
                        loginName:this.nameForm.loginName
                    })
                    if(res){
                        this.$message.success(this.$t('index.alter_success'))
                        this.nameFormVisible=false
                        this.userData.loginName=this.nameForm.loginName
                        this.updateUserInfo();
                    }else if(res===false){
                        this.$message.warning(this.$t('login.js_sign_userName_exist'))
                    }else{
                        this.$message.warning(this.$t('index.alter_fail'))
                    }
                }
            })
        },
        showDeleteModal(data){
            this.$store.commit('setGetUserEmailCodeFlagHeader',true)
        },
        //注销账户
        async closeAccount(){
            let res = await this.API.closeAccount({
                id:this.userData.ids
            })
            if(res.success){
                this.$store.commit('setGetUserEmailCodeFlagHeader',false)
                this.$message.success(this.$t('agreement.account_success'))
                sessionStorage.removeItem('token')
                this.$router.push({path:'/login'})
            }else{
                this.$message.warning(this.$t('agreement.account_failed'))
            }
               
        },
        //修改密码
        async submitPwdForm(formName){
            this.$refs[formName].validate(async(valid)=>{
                if(valid){
                    let res = await this.API.updatePwd({
                        id:this.userData.ids,
                        password:md5(this.pwdForm.confirmPwd)
                    })
                    if(res.success){
                        this.$message.success(this.$t('index.alter_success'))
                        this.pwdFormVisible=false
                        this.userData.password=md5(this.pwdForm.confirmPwd);//更新用户信息
                        this.updateUserInfo();
                    }else{
                        this.$message.warning(this.$t('index.alter_fail'))
                    }
                }
            })
        },
        //重置表单
        resetForm(formName,visible) {
            this.$refs[formName].resetFields();
            this[visible]=false
        },
        async getDictionaryBatch(){
            let res = await this.API.getDictionaryBatch({
                dictCodes:'USER_TYPE',
                lang:localStorage.getItem('lang')||'zh_CN'
            })
            this.dictionary = res || {}
        },
        returnUserTypeCode(val){
            if(JSON.stringify(this.dictionary) != "{}"){
                let code = ''
                this.dictionary.USER_TYPE.forEach(item=>{
                    if(val == item.value){
                    code = item.code
                    }
                })
                return code
            }
        },
        //退出
        logout(){
            sessionStorage.removeItem('token')
            this.$router.push({path:'/login'})
        },
        //获取用户信息
        getUserInfo(){
            this.userData=JSON.parse(sessionStorage.getItem('userObj'));
        },
        //更新用户信息
        updateUserInfo(){
            sessionStorage.setItem('userObj',JSON.stringify(this.userData));
        },
        //初始化告警信息
        async initAlarm(){
            this.getAlarmCount()
            this.getAlarmMsg()
        },
        //获取告警数量
        async getAlarmCount(){
            let res_count = await this.API.getAlarmCount({})
            this.alarmCount=res_count;
        },
        //获取告警信息
        async getAlarmMsg(){
            let res = await this.API.getAlarmMsg({})
            this.alarmList=res;
        },
        //删除单条告警信息
        async delAlarmMsg(index,inverterSn,errorCode){
            let res = await this.API.delAlarmMsg({
                index: this.alarmCount-index-1,
                inverterSn: inverterSn,
                errorCode: errorCode,
            })
            if(this.comm.showMsg(res)){
                this.initAlarm()
            }
        },
        //删除全部告警信息
        async delAllAlarmMsg(index,inverterSn,errorCode){
            let res = await this.API.delAllAlarmMsg({})
            if(res!==null){
                this.$message.success(this.$t('index.control_success'))
            }
            this.initAlarm()
        }
    }
}
</script>

<style lang="less">
@color_box_bg:#EFEFEF;
@color_title:#444;
@color_text:#636162;
@color_unit:#636162;
@color_light:#ff8920;
@border_bottom:1px dashed #D1D1D1;
@border_radius:3px;
@color_unit:#8a8a8a;
.header-container header{
    background:#4E4D52;
    height: 70px;
    img{
        height: 40px;
        vertical-align: baseline;
        position: absolute;
        top: 15px;
        left: 49px;
    }
    ul.navbar{
        float: right;
        >li{
            
            float: left;
            list-style: none;
            color:#999;
            font-size: 14px;
            cursor: pointer;
            .el-dropdown{
                color:#999;
            }
        }
        .padding,.el-dropdown-link{
            padding: 25px 10px;
            display: inline-block;
            &:hover{
                background: rgba(255,255,255,.1);
            }
        }
        .language{
            .el-dropdown-menu__item {
                list-style: none;
                line-height: 25px;
                padding: 0 20px;
                margin: 0;
                font-size: 14px;
                color: #606266;
                cursor: pointer;
                outline: 0;
                border-bottom: 1px dashed rgba(0,0,0,0.1);
            }
        }
    }
    .icon-warning-round{
        color: red;
        position: absolute;
        top: 20px;
        right: 0px;
        font-size: 14px;
    }
}
.el-dropdown-menu.alarmBox{
    color:@color_text;
    min-width: 300px;
    // background: @color_box_bg;
    .box_header{
        padding: 10px;
        max-width: 357px;
        line-height: 25px;
        p{
            margin: 0;
            span{
                color: @color_light;
            }
        }
        .right{
            text-align: right;
        }
    }
    .box_body{
        >li{
            border-bottom: 1px solid #efefef;
            padding: 6px 10px;
            font-size: 14px;
        }
        .info{
            padding: 0;
            border:none;
            background: transparent;
            cursor: default;
            .icon-warning{
                color: #faad14;
            }
            .pointer{
                cursor: pointer;
            }
            div{
                width: 300px;
                padding:0 15px 0 5px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                display: inline-block;
            }
        }
    }
    .box_footer{
        text-align: center;
        .el-link {
            color: @color_light;
        }
        &.handle{
            padding: 5px 10px;
            span{
                float: right;
                padding-left: 10px;
                i{
                    font-size: 20px;
                    &:hover{
                        color: @color_light;
                        cursor: pointer;
                    }
                }
            }
        }
    }
    .el-dropdown-menu--small .el-dropdown-menu__item {
        padding: 0;
    }
    
}
ul.popover{
    li{
        padding: 5px 0;
        &:not(:last-child){
            border-bottom: 1px solid #efefef;
        }
    }
}
</style>